<?php
declare(strict_types=1);

namespace SixShop\Balpay\Controller;


use SixShop\Balpay\Entity\ExtensionBalpayLogEntity;
use SixShop\Balpay\Enum\BalpayLogTypeEnum;
use SixShop\Core\Request;
use SixShop\System\Middleware\MacroPageMiddleware;
use think\Response;
use function SixShop\Core\page_response;
use function SixShop\Core\success_response;

class LogController
{
    protected array $middleware = [
        MacroPageMiddleware::class
    ];

    public function index(Request $request, ExtensionBalpayLogEntity $entity): Response
    {
        $data = $request->get([
            'user_id/d' => 0,
            'type/d' => 0,
        ]);
        return page_response($entity->getList($data['user_id'], BalpayLogTypeEnum::tryFrom($data['type']), $request->pageAndLimit()));
    }

    public function save(Request $request, ExtensionBalpayLogEntity $entity): Response
    {
        $data = $request->post([
            'user_id/d',
            'amount/f',
            'type/d',
            'description/s',
        ]);
        validate([
            'user_id' => 'require|integer|gt:0',
            'amount' => 'require|float|gt:0',
            'type' => 'require|in:1,2',
            'description' => 'require|string',
        ], [
            'user_id.require' => '用户ID不能为空',
            'user_id.integer' => '用户ID必须为整数',
            'user_id.gt' => '用户ID必须大于0',
            'amount.require' => '金额不能为空',
            'amount.float' => '金额必须为数字',
            'amount.gt' => '金额必须大于0',
            'type.require' => '类型不能为空',
            'type.in' => '类型必须为1或2',
            'description.require' => '描述不能为空',
        ])->check($data);
        $entity->change(
            $data['user_id'],
            $data['amount'],
            BalpayLogTypeEnum::from($data['type']),
            $data['description']
        );
        return success_response($entity);
    }
}